package org.myh.excel.properties;



import org.myh.excel.convert.TerminalConvert;
import org.myh.excel.uitl.ClassUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * ClassName: PropertiesUtil
 * Description:
 * date: 2024/3/23 21:53
 *
 * @author Yu Han
 * @since JDK 1.8
 */
public class PropertiesObject<T> implements PropertiesReader, PropertiesResource {

    private Properties properties;
    private InputStream inputStream;
    private String path;
    private final static TerminalConvert terminalConvert = new TerminalConvert("-");

    public PropertiesObject(String path) throws IOException {
        this.path = path;
        refresh();
    }

    public Properties getJDBCProperties(String prefix) {
        Properties properties = new Properties();
        Set<String> set = this.properties.stringPropertyNames();
        for (String key : set) {
            String convert = terminalConvert.convert(prefix, key);
            properties.put(convert.trim(), this.properties.getProperty(key).trim());
        }

        return properties;
    }


    /**
     * 将属性文件赋值给对象
     *
     * @param type   传入过来的对象
     * @param prefix properties内容的前缀 如： db.url 传入db即可
     * @return 当前赋值完成的对象
     */
    public T propertiesToObject(T type, String prefix) {
        Map<String, String> map = new HashMap<>(properties.size());

        Set<String> set = this.properties.stringPropertyNames();
        for (String key : set) {
            String convert = terminalConvert.convert(prefix, key);
            map.put(convert, this.properties.getProperty(key));
        }

        // 通过setProperty方法为属性赋值
        ClassUtil<T> classUtil = new ClassUtil<>();
        try {
            classUtil.setFieldsByNames(type, map);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return (T) type;
    }

    /**
     * 刷新
     *
     * @throws IOException
     */
    public void refresh() throws IOException {
        getCurrentClassLoaderPropertiesResource(this.path);
        getProperties(getInputStream());
    }

    @Override
    public Properties getProperties(InputStream inputStream) throws IOException {
        properties = new Properties();
        properties.load(this.inputStream);
        return null;
    }

    @Override
    public void getCurrentClassLoaderPropertiesResource(String path) throws IOException {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        URL resource = contextClassLoader.getResource(path);
        this.inputStream = resource.openStream();
    }

    @Override
    public InputStream getInputStream() {
        return this.inputStream;
    }

}
